package common

import (
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/protocol"
	"mall_admin_api/biz/consts"
	"mall_admin_api/biz/model"
	"mall_admin_api/biz/model/admin"
	"mall_admin_api/biz/model/admin_error_code"
	"net/http"
)

type Response struct {
	c *app.RequestContext
}

type SuccessResponse struct {
	Code admin_error_code.ErrorCode `json:"code"`
	Data interface{}                `json:"data"`
}

type SuccessWithPageResponse struct {
	Code        admin_error_code.ErrorCode `json:"code"`
	Data        interface{}                `json:"data"`
	CurrentPage int                        `json:"current_page"`
	Total       int64                      `json:"total"`
}

func NewResponse(c *app.RequestContext) *Response {
	return &Response{c: c}
}

func (r *Response) SetCookie(name, value string, maxAge int, path, domain string, sameSite protocol.CookieSameSite, secure, httpOnly bool) *Response {
	r.c.SetCookie(name, value, maxAge, path, domain, sameSite, secure, httpOnly)
	return r
}

func (r *Response) Success(data ...interface{}) {
	var info interface{}
	if len(data) == 0 {
		info = make(map[string]interface{})
	} else {
		info = data[0]
	}
	r.c.JSON(http.StatusOK, SuccessResponse{
		Data: info,
	})
}

func (r *Response) SuccessWithPage(data interface{}, total int64, page int) {
	if data == nil {
		data = make(map[string]interface{})
	}
	r.c.JSON(http.StatusOK, SuccessWithPageResponse{
		Code:        200,
		Data:        data,
		Total:       total,
		CurrentPage: page,
	})
}

func (r *Response) ServerError(err error) {
	r.c.JSON(http.StatusOK, admin.BaseResponse{Code: admin_error_code.ErrorCode_ServerError, Message: err.Error()})
}

func (r *Response) ParamsError(err error) {
	r.c.JSON(http.StatusOK, admin.BaseResponse{
		Code:    admin_error_code.ErrorCode_ParamsError,
		Message: err.Error(),
	})
}

func (r *Response) GetAdministratorInfo() *model.Administrator {
	var info = &model.Administrator{}
	i, exist := r.c.Get(consts.JWTAdminInfo)
	if exist {
		return i.(*model.Administrator)
	}

	return info
}

func (r *Response) GetBizInfo() *model.Biz {
	var info = &model.Biz{ID: 1}

	return info
}

func (r *Response) GetRequestContext() *app.RequestContext {
	return r.c
}
